<template>
    <div class="container">
        <a-form ref="loginForm" :model="search" autocomplete="off" @keyup.enter="handleSearch()">
            <iSearch>
                <template #FormData>
                    <a-form-item>
                        <iInput v-model:value="search.account" tip="账号" placeholder="请输入管理员登录账号"></iInput>
                    </a-form-item>
                    <a-form-item>
                        <iInput v-model:value="search.name" tip="姓名" placeholder="请输入管理员姓名"></iInput>
                    </a-form-item>
                    <a-form-item>
                        <iSelect v-model:value="search.role_ids" mode="multiple" placeholder="请选择角色" :option="AdminRoleData" index="id" label="role_name" tip="角色"></iSelect>
                    </a-form-item>
                </template>
                <template #Button>
                    <a-button type="primary" @click="handleSearch">查询</a-button>
                    <a-button @click="handleReset">重置</a-button>
                    <a-button type="primary" danger v-iscan="['auth:admin:add']" @click="handleAdd">添加</a-button>
                </template>
            </iSearch>
        </a-form>

        <iTable @search="handlePagination" :total="total" :columns="columns" :tableData="tableData" :loading="loading">
            <template #state="{ record }">
                <a-tag :color="FuncDbAdminState(record.state || 0).color">{{ FuncDbAdminState(record.state || 0).label }}</a-tag>
            </template>
            <template #account="{ record }">
                <div>
                    {{ record.name }}
                    （ <span style="text-decoration: underline;font-weight: bold;">{{ record.account }}</span>
                        <span style="cursor: pointer;margin-left: 5px" @click="handleCopyAccount(record.account)">
                            <CopyTwoTone />
                        </span>
                    ）
                </div>
            </template>

            <template #role_name="{ record }">
                <a-tag v-if="record.id == 10001" color="#f50">{{ record.role_name[0] }}</a-tag>
                <template v-else>
                    <a-tag v-for="(item,index) in record.role_name" :color="RandomColor(index)">{{ item }}</a-tag>
                </template>
            </template>

            <template #operate="{ record }">
                <a-flex gap="small" horizontal v-if="record.id !== 10001">
                    <a-button type="link" @click="handleEdit(record.id)" v-iscan="['auth:admin:edit']">编辑</a-button>
                    <iDelete :auth="['auth:admin:del','disabled']" @delete="handleDelete(record.id)"></iDelete>
                </a-flex>
            </template>
        </iTable>


        <a-drawer :title="(formState.id || 0) > 0 ? '编辑管理员': '添加管理员'" rootClassName="full-modal-drawer" width="40%" :open="EditVisible" @close="handleEditClose()" :loading="EditLoading">
            <a-form ref="formStateRef" :model="formState" autocomplete="off" :rules="formStateRule" layout="vertical">
                <a-form-item name="account" label="账号">
                    <a-input v-model:value="formState.account" :disabled="(formState.id || 0) > 0" placeholder="请输入登录账号"></a-input>
                </a-form-item>
                <a-form-item name="name" label="姓名">
                    <a-input v-model:value="formState.name" placeholder="请输入管理员姓名" :disabled="(formState.id || 0) === 10001"></a-input>
                </a-form-item>
                <a-form-item name="password" label="密码">
                    <a-input v-model:value="formState.password" :placeholder="(formState.id || 0) > 0?'为空表示不修改密码':'请输入登录密码'"></a-input>
                </a-form-item>
                <a-form-item name="role_ids" label="角色">
                    <a-select v-model:value="formState.role_ids" mode="multiple" style="width: 100%" placeholder="请选择角色">
                        <a-select-option v-for="(item,index) in AdminRoleData" :key="index":value="item.id">{{ item.role_name }}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item name="state" label="状态">
                    <a-radio-group v-model:value="formState.state" name="State">
                        <a-radio v-for="(item,index) in DbAdminState" :disabled="(formState.id || 0) === 10001" :key="index" :value="item.value">{{ item.label }}</a-radio>
                    </a-radio-group>
                </a-form-item>
            </a-form>
            <template #extra>
                <a-space>
                    <a-button @click="handleEditClose()">取消</a-button>
                    <a-button type="primary" @click="handleSubmit()">保存</a-button>
                </a-space>
            </template>
        </a-drawer>

    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { iPb } from '@/protobuf/interface/index'
import { ListAdmin, ReadAdmin, CreateAdmin, UpdateAdmin, DeleteAdmin } from '@/api/admin';
import { ListAdminRole } from '@/api/admin_role';
import { FormInstance } from 'ant-design-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { DbAdminState, FuncDbAdminState } from '@/tool/const'
import { RandomColor } from '@/tool/function'
import { Message } from '@/tool/antdv';
import { TableWidth } from '@/tool/enum'
import useClipboard from 'vue-clipboard3'
const { toClipboard } = useClipboard()


const search = ref<iPb.Admin.IListAdminRequest>(iPb.Admin.ListAdminRequest.create())
const formStateRef = ref<FormInstance>()
const formState = ref<iPb.IDbAdmin>(iPb.DbAdmin.create())
const formStateRule = reactive({
    account: [
        { required: true, message: '请输入管理员登录账号', whitespace: true },
        { pattern: /^[a-zA-Z_](?!.*_.*_)[a-zA-Z0-9_]{4,11}$/ ,message: '账号必须5-12位，只能包含字母、数字和下划线，不能以数字开头，且下划线最多出现一次', trigger: 'change' }
        
    ],
    name: [
        { required: true, message: '请输入管理员姓名', whitespace: true }
    ],
    state: [
        { required: true, message: '请选择状态' }
    ],
    password: [
        { required: true, message: '请输入登入密码', whitespace: true }
    ]
})

const loading = ref<Boolean>(false)
const EditVisible = ref<Boolean>(false)
const EditLoading = ref<Boolean>(false)

const AdminRoleData = ref<Array<iPb.IDbAdminRole>>([])
const tableData = ref<Array<iPb.IDbAdmin>>([])
const total = ref<number>(0)

const handleAdd = () => {
    formStateRule.password = [
        { required: true, message: '请输入登入密码', whitespace: true }
    ]
    formStateRef.value?.resetFields()
    formState.value = iPb.DbAdmin.create()
    EditVisible.value = true
}
const handleEditClose = () => {
    EditVisible.value = false
}

const handleDelete = (id: number) => {
    if(EditLoading.value) {
        return
    }
    EditLoading.value = true
    DeleteAdmin(iPb.Admin.DeleteAdminRequest.create({
        id: id
    })).then((_result: iPb.Admin.IDeleteAdminResponse) => {
        EditLoading.value = false
        Message.success({
            content: "删除成功",
        })
        initList()
    })
}

const handleEdit = (id: number) => {
    formStateRule.password = []
    formStateRef.value?.resetFields()
    if(EditLoading.value) {
        return
    }
    EditLoading.value = true
    const ReadAdminRequest = iPb.Admin.ReadAdminRequest.create({
        id: id
    })
    ReadAdmin(ReadAdminRequest).then((result:iPb.IDbAdmin) => {
        formState.value = iPb.DbAdmin.create(result)
        EditVisible.value = true
        EditLoading.value = false
    }).catch(() => {
        EditLoading.value = false
    })
}

const handleSubmit = () => {
    const formData = formState.value
    formStateRef.value?.validate().then(() => {
        if(EditLoading.value) {
            return
        }
        EditLoading.value = true
        if((formData.id || 0) > 0) {
            UpdateAdmin(formData).then((_result:iPb.Admin.IUpdateAdminResponse) => {
                EditLoading.value = false
                EditVisible.value = false
                Message.success({
                    content: "保存成功",
                })
                initList()
            }).catch(() => {
                EditLoading.value = false
            })
        }else {
            CreateAdmin(formData).then((_result:iPb.Admin.ICreateAdminResponse) => {
                EditLoading.value = false
                EditVisible.value = false
                Message.success({
                    content: "添加成功",
                })
                initList()
            }).catch(() => {
                EditLoading.value = false
            })
        }
    })
}

const handleCopyAccount = (account: string) => {
    toClipboard(account)
    Message.success({
        content: "拷贝成功",
    })
}

const handleReset = () => {
    search.value = iPb.Admin.ListAdminRequest.create()
    initList()
}

const handleSearch = () => {
    initList()
}

const handlePagination = (e: { current: number | undefined; pageSize: number | undefined; }) => {
    initList(e.current, e.pageSize)
}

const initList = (page = 1, limit = 15) => {
    if(loading.value) {
        return
    }
    loading.value = true
    search.value.limit = limit
    search.value.page = page
    ListAdmin(iPb.Admin.ListAdminRequest.create(search.value)).then((result:iPb.Admin.IListAdminResponse) => {
        let R = iPb.Admin.ListAdminResponse.create(result)
        tableData.value = R.data
        total.value = R.count
        loading.value = false
    })
}

const initDbAdminRole = () => {
    ListAdminRole(iPb.Admin.ListAdminRoleRequest.create()).then((result:iPb.Admin.IListAdminRoleResponse) => {
        let R = iPb.Admin.ListAdminRoleResponse.create(result)
        AdminRoleData.value = R.data
    })
}

const columns:TableColumnsType = [
    {
        title: "ID",
        dataIndex: "id",
        width: TableWidth.Id,
    },
    {
        title: "管理员姓名（账号）",
        dataIndex: "account",
        width: TableWidth.Ordinary,
    },
    {
        title: "角色",
        dataIndex: "role_name",
        width: TableWidth.Ordinary,
    },
    {
        title: "状态",
        dataIndex: "state",
        width: TableWidth.Ordinary,
    },
    {
        title: "操作",
        dataIndex: "operate",
        width: TableWidth.Operate,
    }
]

onMounted(() => {
    initList()
    initDbAdminRole()
})


</script>